package netty.protocoltcp;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.util.CharsetUtil;

import java.nio.charset.Charset;

public class MyServerHandler extends SimpleChannelInboundHandler<Message> {
    private int count = 0;

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, Message msg) throws Exception {
        System.out.println("服务器接收到第 " + (++count) + " 条消息: " + msg.getSize() + " " + new String(msg.getMessage(), CharsetUtil.UTF_8));
        String res = "response: " + count;
        ctx.writeAndFlush(new Message(res.length(), res.getBytes()));
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        ctx.close();
    }
}
